/**
 * Copyright (c) Tapas Mobile.  All Rights Reserved.
 *
 * Helper class for android.app.ApplicationLoaders
 *
 * @author DaiHui 
 * @version 1.0
 */

package com.dotools.reflection;

import java.lang.reflect.Method;

public class ReflectApplicationLoaders {
    static Class<?> sClsAppLoaders;
    static Method sMethodGetDefault;
    static Method sMethodGetClassLoader;

    static Object sObjectAppLoaders;

    static {
        ClassLoader clsLoader = ClassLoader.getSystemClassLoader();
        try {
            sClsAppLoaders = clsLoader.loadClass("android.app.ApplicationLoaders");

            sMethodGetDefault = sClsAppLoaders.getDeclaredMethod("getDefault", new Class<?>[] {});

            sMethodGetClassLoader = sClsAppLoaders.getDeclaredMethod("getClassLoader", new Class<?>[] {
                    String.class, String.class, ClassLoader.class
            });
        } catch (Exception e) {
            sClsAppLoaders = null;
        }

        if (sMethodGetDefault != null) {
            try {
                sObjectAppLoaders = sMethodGetDefault.invoke(null, (Object[]) null);
            } catch (Exception e) {
                sObjectAppLoaders = null;
            }
        }
    }

    public static ClassLoader getClassLoader(String zip, String libPath, ClassLoader parent) {
        Object result = null;

        if (sObjectAppLoaders != null && sMethodGetClassLoader != null) {
            try {
                result = sMethodGetClassLoader.invoke(sObjectAppLoaders, zip, libPath, parent);
            } catch (Exception e) {
                result = null;
            }
        }

        return (ClassLoader) result;
    }
}
